package weworkgo

import (
	"errors"
	"fmt"
	"gitee.com/microrain/weworkgo/lib"
	"log"
)

/**
 * 企业微信安装应用授权 url.
 *
 * @param string $preAuthCode 预授权码
 * @param string $redirectUri 回调地址
 * @param string $state
 *
 * @return string
 */
func (p *Provider) GetPreAuthorizationUrl(preAuthCode, redirectUri, state string) string {
	if redirectUri == "" {
		redirectUri = p.Config.RedirectUriInstall
	}
	if preAuthCode == "" {
		preAuthCode = p.getPreAuthCode()
	}

	urlStr := fmt.Sprintf("https://open.work.weixin.qq.com/3rdapp/install?suite_id=%s&pre_auth_code=%s&redirect_uri=%s&state=%s",
		p.Config.SuiteId,
		preAuthCode,
		redirectUri,
		state)

	return urlStr
}

/**
 * 获取预授权码.
 *
 * @return mixed
https://work.weixin.qq.com/api/doc/90001/90143/90601
{
    "errcode":0 ,
    "errmsg":"ok" ,
    "pre_auth_code":"Cx_Dk6qiBE0Dmx4EmlT3oRfArPvwSQ-oa3NL_fwHM7VI08r52wazoZX2Rhpz1dEw",
    "expires_in":1200
}

 * */
var getPreAuthCodeUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_pre_auth_code?suite_access_token="

func (p *Provider) getPreAuthCode() string {

	suiteAccessToken := p.getSuiteToken()

	result, err := lib.HttpGetData(getPreAuthCodeUrl + suiteAccessToken)
	log.Printf("Request getPreAuthCode Response:(%s) %s", p.Config.CorpId, result)
	if err != nil {
		return ""
	}
	response := lib.UnJson(result, new(PreAuthCodeResponse)).(*PreAuthCodeResponse)
	if response == nil {
		log.Printf("Request getPreAuthCode Failed: " + result)
		return ""
	}
	log.Printf("从腾讯服务器取pre_auth_code ===只能消费一次======", response.PreAuthCode)

	return response.PreAuthCode
}

/**
 * 设置授权配置.
 * 该接口可对某次授权进行配置.
 *
https://work.weixin.qq.com/api/doc/90001/90143/90602
 *
 * @return mixed
*/
var setSessionUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/set_session_info?suite_access_token="

func (p *Provider) setSession(sr SetSessionRequest) bool {

	suiteAccessToken := p.getSuiteToken()

	result, err := lib.HttpPostData(setSessionUrl+suiteAccessToken, sr)
	if err != nil {
		log.Printf(err.Error())
		return false

	}
	response := lib.UnJson(result, new(ErrResponse)).(*ErrResponse)
	if response == nil {
		log.Printf("Request setSession Failed: " + result)
		return false
	}
	return true
}

/**
 * 获取企业永久授权码.
 *
 * @param string $authCode 临时授权码，会在授权成功时附加在redirect_uri中跳转回第三方服务商网站，或通过回调推送给服务商。长度为64至512个字节
 *
 * @return mixed
https://work.weixin.qq.com/api/doc/90001/90143/90603
*/
var getPermanentByCodeUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_permanent_code?suite_access_token="

func (p *Provider) GetPermanentByCodeData(authCode string) (*PermanentByCodeResponse, error) {

	suiteAccessToken := p.getSuiteToken()

	data := map[string]string{
		"auth_code": authCode,
	}
	result, err := lib.HttpPostData(getPermanentByCodeUrl+suiteAccessToken, data)
	if err != nil {
		log.Printf(err.Error())
		return nil, err

	}
	response := lib.UnJson(result, new(PermanentByCodeResponse)).(*PermanentByCodeResponse)
	if response == nil {
		return nil, err
	}

	CorpId := response.AuthCorpInfo.Corpid
	p.SetPermanentCode(PermanentCodeCacheKey+p.Config.SuiteId+"_"+CorpId, response.PermanentCode)

	return response, nil
}

/**
 * 获取企业授权信息.
 *
 * @param string $authCorpId
 * @param string $permanentCode
 *
 * @return mixed
https://work.weixin.qq.com/api/doc/90001/90143/90604
*/

var getAuthorizationUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_auth_info?suite_access_token="

func (p *Provider) getAuthorization(authCorpId, permanentCode string) (*AuthorizationResponse, error) {

	suiteAccessToken := p.getSuiteToken()
	data := map[string]string{
		"auth_corpid":    authCorpId,
		"permanent_code": permanentCode,
	}
	result, err := lib.HttpPostData(getAuthorizationUrl+suiteAccessToken, data)
	if err != nil {
		log.Printf(err.Error())
		return nil, err

	}
	response := lib.UnJson(result, new(AuthorizationResponse)).(*AuthorizationResponse)
	if response == nil {
		return nil, errors.New("Request setSession Failed: " + result)
	}

	return response, nil

}

/**
 * 获取应用的管理员列表.
 *
 * @param string $authCorpId
 * @param string $agentId
 *
 * @return mixed
 *
https://work.weixin.qq.com/api/doc/90001/90143/90606
*/
var getManagersUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/get_admin_list?suite_access_token="

func (p *Provider) getManagers(authCorpId, agentId string) (*ManagersResponse, error) {
	suiteAccessToken := p.getSuiteToken()

	data := map[string]string{
		"auth_corpid": authCorpId,
		"agentid":     agentId,
	}
	result, err := lib.HttpPostData(getManagersUrl+suiteAccessToken, data)
	if err != nil {
		log.Printf(err.Error())
		return nil, err

	}
	response := lib.UnJson(result, new(ManagersResponse)).(*ManagersResponse)
	if response == nil {
		return nil, errors.New("Request getManagers Failed: " + result)
	}

	return response, nil
}

/**
 * 获取登录url.
 *
 * @param string      $redirectUri
 * @param string      $scope
 * @param string|null $state
 *
 * @return string
https://work.weixin.qq.com/api/doc/90001/90143/91861
*/
func (p *Provider) getOAuthRedirectUrl(redirectUri, scope, state string) string {

	if scope == "" {
		scope = "snsapi_base"
	}
	urlStr := fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
		p.Config.SuiteId,
		redirectUri,
		scope,
		state)

	return urlStr
}

/**
 * 第三方根据code获取企业成员信息.
 *
 * @param string $code
 *
 * @return mixed
 *
https://work.weixin.qq.com/api/doc/90001/90143/91121
https://work.weixin.qq.com/api/doc/90001/90143/91711

*/
var getUserByCodeUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?suite_access_token="

func (p *Provider) GetUserByCode(code string) (*UserByCodeResponse, error) {

	suiteAccessToken := p.getSuiteToken()
	result, err := lib.HttpGetData(getUserByCodeUrl + suiteAccessToken + "&code=" + code)
	//glog.Debugf("Request GetUserByCode Response:(%s) %s", p.Config.CorpId, result)
	if err != nil {
		return nil, err
	}
	response := lib.UnJson(result, new(UserByCodeResponse)).(*UserByCodeResponse)
	if response == nil {
		return nil, errors.New("Request getUserByCode Failed: " + result)
	}

	return response, nil
}

/**
 * 第三方使用user_ticket获取成员详情.获取访问用户敏感信息
 *
 * @param string $userTicket
 *
 */
var getUserByTicketUrl = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?suite_access_token="

func (p *Provider) GetUserByTicket(userTicket string) (*UserByTicketResponse, error) {

	suiteAccessToken := p.getSuiteToken()
	data := map[string]string{
		"user_ticket": userTicket,
	}
	result, err := lib.HttpPostData(getUserByTicketUrl+suiteAccessToken, data)
	if err != nil {
		log.Printf(err.Error())
		return nil, err

	}
	response := lib.UnJson(result, new(UserByTicketResponse)).(*UserByTicketResponse)
	if response == nil {
		return nil, errors.New("Request GetUserByTicket Failed: " + result)
	}

	return response, nil
}
